package com.xyz.threadPoolAndOther;

import java.util.concurrent.*;

/**
 * @author 肖咉卓
 *
 * 线程池
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        System.out.println(Runtime.getRuntime().availableProcessors());
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                (Runtime.getRuntime().availableProcessors()+1),
                2L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        try {
            for (int i = 1;i <= 10;i++){
                threadPool.execute(() ->{
                    System.out.println(Thread.currentThread().getName()+"\t 办理业务中");
                });
            }
        }finally {
            threadPool.shutdown();
        }
    }

    public void initPool(){
        //ExecutorService threadPool = Executors.newFixedThreadPool(5);//一个池子5个受理线程，类似一个银行有5个受理窗口
        //ExecutorService threadPool = Executors.newSingleThreadExecutor();//一个池子1个受理线程，类似一个银行有1个受理窗口
        ExecutorService threadPool = Executors.newCachedThreadPool();//一个池子N个受理线程，可扩容可伸缩,根据并发量自动调节
        try {
            //模拟有10个顾客办理业务，目前池子里有5个工作人员提供服务
            for (int i = 1;i <= 10;i++){
                final int zhi=(int)(Math.random()*10);
                try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
                threadPool.execute(() ->{
                    System.out.println(Thread.currentThread().getName()+"\t 办理业务中："+zhi+"秒");
                    try { TimeUnit.SECONDS.sleep(zhi); } catch (InterruptedException e) { e.printStackTrace(); }
                    System.out.println("======"+Thread.currentThread().getName()+"\t 办理完成");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
}
